package com.itheima.health.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Menu;
import com.itheima.health.pojo.Permission;
import com.itheima.health.pojo.Role;
import com.itheima.health.pojo.User;
import com.itheima.health.service.RoleService;
import com.itheima.health.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@WebFilter(urlPatterns = "/*")
@Slf4j
public class PermissionFilter implements Filter {
    @Autowired
    private UserService us;
    @Autowired
    private RoleService rs;

    //定义集合，存放无需登录的地址
    private String[] uris=new String[]{
            "/user/login",
            "/user/logout",
            "/mobile/**"
    };
    //定义集合，存放需要权限的地址
    private Map<String,String> urisMap =new HashMap<>();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //添加需要权限的地址
        urisMap.put("/checkitem/add","CHECKITEM_ADD");
        urisMap.put("/checkitem/delete","CHECKITEM_DELETE");
        urisMap.put("/checkitem/edit","CHECKITEM_EDIT");
        urisMap.put("/checkitem/findPage","CHECKITEM_QUERY");

        urisMap.put("/checkgroup/add","CHECKGROUP_ADD");
        urisMap.put("/checkgroup/deleteCheckGroupitemById","CHECKGROUP_DELETE");
        urisMap.put("/checkgroup/edit","CHECKGROUP_EDIT");
        urisMap.put("/checkgroup/findPage","CHECKGROUP_QUERY");

        urisMap.put("/setmeal/add","SETMEAL_ADD");
        //urisMap.put("/setmeal","SETMEAL_DELETE");
        //urisMap.put("/setmeal","SETMEAL_EDIT");
        urisMap.put("/setmeal/findPage","SETMEAL_QUERY");

        //urisMap.put("","ORDERSETTING");
        urisMap.put("/report","REPORT_VIEW");

        //urisMap.put("","MENU_ADD");
        //urisMap.put("","MENU_DELETE");
        //urisMap.put("","MENU_EDIT");
        //urisMap.put("","MENU_QUERY");
        //
        //urisMap.put("","ROLE_ADD");
        //urisMap.put("","ROLE_DELETE");
        //urisMap.put("","ROLE_EDIT");
        //urisMap.put("","ROLE_QUERY");
        //
        //urisMap.put("","USER_ADD");
        //urisMap.put("","USER_DELETE");
        //urisMap.put("","USER_EDIT");
        //urisMap.put("","USER_QUERY");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest) servletRequest;
        HttpServletResponse resp=(HttpServletResponse) servletResponse;

        //得到URI
        String reqUri = req.getRequestURI();
        log.info("[登录检查]请求URI：{}",reqUri);

        //判断是否需要登录
          //不需要，放行
        if (checkURI(reqUri)){
            log.info("无需登录，放行");
            filterChain.doFilter(req,resp);
            return;
        }
          //需要，判断是否登录
        if (req.getSession().getAttribute("user")!=null){
            log.info("已登录");

            //判断是否有权限
              //有，放行
            User user = (User) req.getSession().getAttribute("user"); //改了
            user.setRoles(us.findRole(user.getId()));
            req.getSession().setAttribute("user",user);
            log.info("用户信息：{}",user);
            if (checkPermission(reqUri, user)){
                log.info("权限匹配，放行");
                filterChain.doFilter(req,resp);
                return;
            }else{//无，拒绝访问
                log.info("无此权限");
                resp.setContentType("text/html;charset=utf-8");
                resp.getWriter().write(JSON.toJSONString(new Result(false,"无此权限")));
                return;
            }
        }
        log.info("未登录");
        resp.setContentType("text/html;charset=utf-8");
        resp.getWriter().write(JSON.toJSONString(new Result(false,"未登录")));
    }

    final AntPathMatcher apm=new AntPathMatcher();
    private boolean checkURI(String reqUri){
        for (String uri : uris) {
            if (apm.match(uri,reqUri)){
                return true;
            }
        }
        return false;
    }

    private boolean checkPermission(String reqUri, User user){
        Set<String> keySet = urisMap.keySet();
        //判断是否需要权限
        for (String s : keySet) {
            //若匹配，则需要权限
            if (apm.match(s,reqUri)){
                //判断是否有权限
                Set<Role> roles = user.getRoles();
                for (Role role : roles) {
                    Set<Permission> permissions = rs.findPermission(role.getId());
                    for (Permission permission : permissions) {
                        //有，则返回true
                        if (permission.getKeyword().equals(urisMap.get(reqUri))){
                            return true;
                        }
                    }
                }
                //无，则返回false
                return false;
            }
        }
          //若不匹配，则可直接访问
        return true;
    }

}
